package icursoft.educationms.ui.user;

import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okgo.callback.StringCallback;
import com.readystatesoftware.systembartint.SystemBarTintManager;

import org.json.JSONException;
import org.json.JSONObject;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import icursoft.educationms.BaseActivity;
import icursoft.educationms.EducationMSApplication;
import icursoft.educationms.R;
import icursoft.educationms.bean.StudentInfoBO;
import icursoft.educationms.http.HttpCallBack;
import icursoft.educationms.http.HttpResult;
import icursoft.educationms.servive.PreferencesService;
import icursoft.educationms.util.CommUtil;
import icursoft.educationms.util.Const;
import icursoft.educationms.util.MachTalkUtil;
import icursoft.educationms.util.TimeCountDown;

public class ForgotPasswordActivity extends BaseActivity {
    private String mPhone = null;
    private String mEmail = null;
    private String mValidationCode;
    private String mUser = null;
    private SystemBarTintManager tintManager;
    private EditText mUserView, mValidationCodeView, txtNewPassword,
            txtConfirmPassword;
    private TextView btnSendCode;
    private View mLoginFormView;
    private String TAG = ForgotPasswordActivity.class.getSimpleName();
    String newPassword, newConfirmPassword;
    private final static int REGISTER_TYPE_TELEPHONE = 1;
    private final static int REGISTER_TYPE_EMAIL = 2;
    private int mRegisterType = 1;
    String validationEmail, validationPhone, validationCode = null;
    private ImageView iv_back;
    TextView btn_initpwd;
    boolean cancel = false;
    boolean flag_validate_notnull = false;
    boolean flag_username_notnull = false;
    boolean flag_pwd_notnull = false;
    boolean flag_cpwd_notnull = false;
    int FLAG_USERNAME = 1;
    int FLAG_PWD = 2;
    int FLAG_CPWD = 3;
    int FLAG_VALIDATE = 4;
    LinearLayout ll_username_delete;
    LinearLayout ll_pwd_delete;
    LinearLayout ll_cpwd_delete;
    TextView title_tv;
    private int i;

    public void setupViews() {

        title_tv = getView(R.id.title_tv);
        title_tv.setText(R.string.title_activity_forgot_password);

        ll_username_delete = (LinearLayout) findViewById(R.id.ll_num_delete);
        ll_pwd_delete = (LinearLayout) findViewById(R.id.ll_pwd_delete);
        ll_cpwd_delete = (LinearLayout) findViewById(R.id.ll_confim_pwd_delete);
        mUserView = (EditText) findViewById(R.id.register_edittext_num);
        mUserView.requestFocus();
        txtNewPassword = (EditText) findViewById(R.id.password_edittext_password);
        txtConfirmPassword = (EditText) findViewById(R.id.password_edittext_password_ensure);
        mValidationCodeView = (EditText) findViewById(R.id.register_edittext_validate_code);
        getView(R.id.left_layout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mUserView.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean isFocuse) {
                if (isFocuse && flag_username_notnull) {
                    ll_username_delete.setVisibility(View.VISIBLE);
                } else {
                    ll_username_delete.setVisibility(View.GONE);
                }
            }
        });
        txtConfirmPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean isFocuse) {
                if (isFocuse && flag_cpwd_notnull) {
                    ll_cpwd_delete.setVisibility(View.VISIBLE);
                } else {
                    ll_cpwd_delete.setVisibility(View.GONE);
                }
            }
        });
        txtNewPassword.setOnFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View arg0, boolean isFocuse) {
                if (isFocuse && flag_pwd_notnull) {
                    ll_pwd_delete.setVisibility(View.VISIBLE);
                } else {
                    ll_pwd_delete.setVisibility(View.GONE);
                }
            }
        });

        mUserView.addTextChangedListener(new EditChangedListener(FLAG_USERNAME));
        mValidationCodeView.addTextChangedListener(new EditChangedListener(FLAG_VALIDATE));
        txtNewPassword.addTextChangedListener(new EditChangedListener(FLAG_PWD));
        txtConfirmPassword.addTextChangedListener(new EditChangedListener(FLAG_CPWD));

        ll_username_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                mUserView.getText().clear();
            }
        });
        ll_pwd_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                txtNewPassword.getText().clear();
            }
        });
        ll_cpwd_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                txtConfirmPassword.getText().clear();
            }
        });

        btn_initpwd = (TextView) findViewById(R.id.image_button_init_password);
        btn_initpwd.setOnClickListener(this);
        btn_initpwd.setBackgroundResource(R.mipmap.iv_btn_unwrite);
         btn_initpwd.setClickable(true);
        btnSendCode = (TextView) findViewById(R.id.image_button_get_validation);
        btnSendCode.setOnClickListener(this);
    }
    @Override
    protected void onDestroy() {
        SMSSDK.unregisterAllEventHandler();
        super.onDestroy();

    }
    @Override
    protected void initialized() {
        SMSSDK.initSDK(this, "1cb1009f4ed60", "781244c832b4b22967b4029afa80f220");
        //注册回调监听接口
        final EventHandler eventHandler = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object o) {
                Message message = new Message();
                message.arg1 = event;
                message.arg2 = result;
                message.obj = o;
                handler.sendMessage(message);
            }
        };
        SMSSDK.registerEventHandler(eventHandler);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_forgot_password;
    }


    @Override
    public void onClick(View view) {
        mValidationCode = mValidationCodeView.getText().toString();
        newPassword = txtNewPassword.getText().toString();
        newConfirmPassword = txtConfirmPassword.getText().toString();
        mUser = mUserView.getText().toString();
        switch (view.getId()) {
            case R.id.image_button_get_validation:
                mUser = mUserView.getText().toString();
                if (TextUtils.isEmpty(mUser)) {
                    CommUtil.showToast(mContext, R.string.prompt_username_with_tip, Toast.LENGTH_SHORT);
                    return;
                }
                if (CommUtil.isMobilePhone(mUser)) {
                    validationPhone = mUser;
                } else {
                    CommUtil.showToast(mContext,
                            R.string.prompt_phone_or_email, Toast.LENGTH_SHORT);
                    return;
                }
                if (CommUtil.judgePhoneNums(this,mUser)) {
                    SMSSDK.getVerificationCode("86", mUser);
                    //timeCountDown.start();
                    btnSendCode.setClickable(false);
                    i = 60;
                    btnSendCode.setText("重新发送(" + i + ")");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (; i > 0; i--) {
                                handler.sendEmptyMessage(1);
                                if (i <= 0) {
                                    break;
                                }
                                try {
                                    Thread.sleep(1000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                            handler.sendEmptyMessage(2);
                        }
                    }).start();
                    break;
                }else {
                    mUserView.setText("");
                }
                //MachTalkUtil.sendValidationCode(codeCallback, mUser, "2");
                break;
            case R.id.image_button_init_password:
                if (attemptInitPwd()) {
//                    MachTalkUtil.resetPassWord(this,resetCallBack, mUserView.getText().toString(),
//                             txtNewPassword.getText().toString());
                }
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                btnSendCode.setText("重新发送" + i + "s");
            } else if (msg.what == 2) {
                btnSendCode.setText("获取验证码");
                btnSendCode.setClickable(true);
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    //回调完成
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        //提交验证码成功
                        Log.e(TAG, "handleMessage: " + event + "," + result + "," + data);
                        //将登录信息保存至数据库
                        /*App.editor.putString(App.USERNAME_REGISTER , mPhoneEdt.getText().toString());
                        App.editor.putString(App.USERPWD_REGISTER , mPwdEdt.getText().toString());
                        App.editor.commit();*/
                        StudentInfoBO userLoginInfo = new StudentInfoBO();
                        userLoginInfo.setPhone(mUserView.getText().toString());
                        userLoginInfo.save();
                        MachTalkUtil.resetPassWord(ForgotPasswordActivity.this,resetCallBack, mUserView.getText().toString(),
                             txtNewPassword.getText().toString());
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        boolean smart = (Boolean) data;
                        if (smart){
                        }else {
                            //获取验证码成功
                            Toast.makeText(getApplicationContext(), "正在获取验证码",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else if (event == SMSSDK.EVENT_GET_SUPPORTED_COUNTRIES) {
                        //返回支持发送验证码的国家列表
                    }
                }else  if (result == SMSSDK.RESULT_ERROR){
                    Throwable throwable = (Throwable) data;
                    throwable.printStackTrace();
                    JSONObject object;
                    try {
                        object = new JSONObject(throwable.getMessage());
                        //Toast.makeText(mContext, "错误代码：" + object.optInt("status")+","+object.optString("detail"), Toast.LENGTH_SHORT).show();
                        mValidationCodeView.setError(object.optString("detail"));
                        Log.e(TAG, "错误代码：" + object.optInt("status")+","+object.optString("detail"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    public boolean attemptInitPwd() {


        if (TextUtils.isEmpty(mUser)) {
            CommUtil.showToast(mContext, R.string.prompt_phone,
                    Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(mValidationCode)) {
            CommUtil.showToast(mContext, R.string.prompt_validation_code,
                    Toast.LENGTH_SHORT);
            return false;
        }
        if (TextUtils.isEmpty(newConfirmPassword)) {
            CommUtil.showToast(mContext, R.string.confirm_field_required,
                    Toast.LENGTH_SHORT);
            return false;
        }
        if (!TextUtils.isEmpty(newPassword)
                && !TextUtils.isEmpty(newConfirmPassword)
                && !newPassword.equals(newConfirmPassword)) {
            CommUtil.showToast(mContext, R.string.error_inconsistent_password,
                    Toast.LENGTH_SHORT);
            return false;
        }

        if (TextUtils.isEmpty(newPassword)) {
            CommUtil.showToast(mContext, R.string.prompt_password,
                    Toast.LENGTH_SHORT);
            return false;
        } else if (newPassword.length() < Const.MIN_PASSWORD_LENGTH) {
            CommUtil.showToast(mContext, R.string.error_short_limited_password,
                    Toast.LENGTH_SHORT);
            return false;
        } else if (newPassword.matches("[0-9]+")
                || newPassword.matches("[a-zA-Z]+")
                || newPassword.matches("[^0-9a-zA-Z]+")) {
            CommUtil.showToast(mContext, R.string.error_password_limit,
                    Toast.LENGTH_SHORT);
            return false;
        }

        SMSSDK.submitVerificationCode("86", mUser, mValidationCode);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    class EditChangedListener implements TextWatcher {
        private CharSequence temp;// 监听前的文本
        private int editStart;// 光标开始位置
        private int editEnd;// 光标结束位置
        private final int charMaxNum = 10;
        int flag;

        public EditChangedListener(int flag) {
            super();
            this.flag = flag;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            temp = s;
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                                  int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {

            if (temp.length() > 0) {
                if (flag == FLAG_USERNAME) {
                    flag_username_notnull = true;
                }
                if (flag == FLAG_PWD) {
                    flag_pwd_notnull = true;

                }
                if (flag == FLAG_CPWD) {
                    flag_cpwd_notnull = true;

                }
                if (flag == FLAG_VALIDATE) {
                    flag_validate_notnull = true;

                }
            } else {
                if (flag == FLAG_USERNAME) {
                    flag_username_notnull = false;
                }
                if (flag == FLAG_PWD) {
                    flag_pwd_notnull = false;
                }
                if (flag == FLAG_CPWD) {
                    flag_cpwd_notnull = false;

                }
                if (flag == FLAG_VALIDATE) {
                    flag_validate_notnull = true;

                }
            }
            if (flag_pwd_notnull && flag_username_notnull && flag_cpwd_notnull && flag_validate_notnull) {
                btn_initpwd.setClickable(true);
                btn_initpwd.setBackgroundResource(R.drawable.btn_three_states);
            } else {
                btn_initpwd.setClickable(false);
                btn_initpwd.setBackgroundResource(R.mipmap.iv_btn_unwrite);
            }
            if (flag_username_notnull && mUserView.isFocused()) {
                ll_username_delete.setVisibility(View.VISIBLE);
            } else {
                ll_username_delete.setVisibility(View.GONE);
            }
            if (flag_pwd_notnull && txtNewPassword.isFocused()) {
                ll_pwd_delete.setVisibility(View.VISIBLE);
            } else {
                ll_pwd_delete.setVisibility(View.GONE);
            }
            if (flag_cpwd_notnull && txtConfirmPassword.isFocused()) {
                ll_cpwd_delete.setVisibility(View.VISIBLE);
            } else {
                ll_cpwd_delete.setVisibility(View.GONE);
            }

        }
    }
    StringCallback resetCallBack = new StringCallback() {
        @Override
        public void onSuccess(String str, okhttp3.Call call, okhttp3.Response response) {
            //上传成功
            Log.e("wangshu", "reset===="+str);
            HttpResult param = EducationMSApplication.GSON.fromJson(str , HttpResult.class);
            if (param.getMsg() >= 0) {
                PreferencesService.getInstance(mContext).setIsLogin(false);
                finish();
//            startActivity(InticareDActivity.class);
            } else {
                CommUtil.showToast(mContext, param.getMsgbox().toString(),  Toast.LENGTH_SHORT);
            }
        }
        @Override
        public void upProgress(long currentSize, long totalSize, float progress, long networkSpeed) {
            //这里回调上传进度(该回调在主线程,可以直接更新ui)
        }
    };

}



